﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net.Mail;
using System.Web;

namespace IQReportes.Utils
{
    /// <summary>
    /// Clase para validar atributo de email
    /// </summary>
    public class EmailAttribute:ValidationAttribute
    {
        /// <summary>
        /// constructor
        /// </summary>
        public EmailAttribute() 
            : base("El campo {0} debe contener un email válido")
        { }
        /// <summary>
        /// validar email
        /// </summary>
        /// <param name="value">objeto a validar</param>
        /// <param name="validationContext">contexto actual</param>
        /// <returns>éxito o error</returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                try
                {
                    var address = new MailAddress(value.ToString()).Address;
                }
                catch (FormatException)
                {
                    var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                    return new ValidationResult(errorMessage);
                }        
            }
            return ValidationResult.Success;
        }

    }
}